package com.geek.novel.utils

import android.content.Context
import android.graphics.Bitmap
import android.graphics.Matrix
import android.renderscript.Allocation
import android.renderscript.Element
import android.renderscript.RenderScript
import android.renderscript.ScriptIntrinsicBlur

/**
 * 图片工具类
 */
object ImageUtil {

    /**毛玻璃效果*/
    fun setImageStackBlur(context: Context?, sentBitmap: Bitmap, radius: Int): Bitmap {
        val bitmap = sentBitmap.copy(sentBitmap.config, true)
        val rs = RenderScript.create(context)
        val input = Allocation.createFromBitmap(rs, sentBitmap, Allocation.MipmapControl.MIPMAP_NONE, Allocation.USAGE_SCRIPT)
        val output = Allocation.createTyped(rs, input.type)
        val script = ScriptIntrinsicBlur.create(rs, Element.U8_4(rs))
        script.setRadius(radius.toFloat())
        script.setInput(input)
        script.forEach(output)
        output.copyTo(bitmap)
        sentBitmap.recycle()
        rs.destroy()
        input.destroy()
        output.destroy()
        script.destroy()
        return bitmap
    }
	
	/**
	 * 变换位图大小
	 */
	fun imageCompress(bitmap: Bitmap, width: Int, height: Int): Bitmap{
		val bitmapWidth = bitmap.width
		val bitmapHeight = bitmap.height
		
		val scaleW = width / bitmapWidth.toFloat()
		val scaleH = height / bitmapHeight.toFloat()
		val transformation = Matrix()
		transformation.preScale(scaleW, scaleH)
		
		//根据缩放比例获取新图
		return Bitmap.createBitmap(bitmap, 0, 0, bitmapWidth, bitmapHeight, transformation, true)
	}

}